import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit'

// 商品的 Type 类型
type GoodsType = {
  id: number
  goods_name: string
  goods_img: string
  goods_price: number
  goods_count: number
  goods_state: boolean
}

// 接口响应回来的数据结构
interface IResponseType {
  status: number
  message: string
}

// 商品列表的数据结构
interface IGoodsResponse extends IResponseType {
  list: GoodsType[]
}

// 初始值
const initialState: {
  list: Array<GoodsType>
} = {
  list: []
}

// 获取商品列表的异步 Action
export const fetchGoodsList = createAsyncThunk('goods/fetchGoodsList', async () => {
  const response = await fetch('https://www.escook.cn/api/cart')
  const result = (await response.json()) as IGoodsResponse
  return result
})

const goodsSlice = createSlice({
  name: 'goods',
  initialState,
  reducers: {
    // 更新商品的数量
    updateGoodsCount(state, action: PayloadAction<{ id: number; value: number }>) {
      const findResult = state.list.find((x) => x.id === action.payload.id)
      findResult && (findResult.goods_count = action.payload.value)
    },
    // 更新商品的状态
    updateGoodsState(state, action: PayloadAction<{ id: number; value: boolean }>) {
      const findResult = state.list.find((x) => x.id === action.payload.id)
      findResult && (findResult.goods_state = action.payload.value)
    },
    // 更新每件商品的勾选状态
    updateAllState(state, action: PayloadAction<{ value: boolean }>) {
      state.list.forEach((x) => (x.goods_state = action.payload.value))
    }
  },
  extraReducers: (builder) => {
    builder.addCase(fetchGoodsList.fulfilled, (state, action) => {
      state.list = action.payload.list
    })
  }
})

export const { updateGoodsCount, updateGoodsState, updateAllState } = goodsSlice.actions
export default goodsSlice.reducer
